<template>
  <div
    class="v-switch"
    :class="{
      [`v-switch-${size}`]: size,
      'is-disabled': disabled,
      'is-checked': checked,
    }"
    @click="switchValue"
  >
    <input
      class="v-switch__input"
      type="checkbox"
      role="switch"
      ref="inputRef"
      :name="name"
      :disabled="disabled"
      @keydown.enter="switchValue"
    />
    <div class="v-switch__core">
      <div class="v-switch__core-inner">
        <span
          class="v-switch__core-inner-text"
          v-if="activeText || inactiveText"
          >{{ checked ? activeText : inactiveText }}</span
        >
      </div>
      <div class="v-switch__core-action"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue'
import type { SwitchProps, SwitchEmits } from './types'

const props = withDefaults(defineProps<SwitchProps>(), {
  activeValue: true,
  inactiveValue: false,
})
const emits = defineEmits<SwitchEmits>()

const innerValue = ref(props.modelValue)
const inputRef = ref<HTMLInputElement>()

const checked = computed(() => innerValue.value === props.activeValue)

const switchValue = () => {
  if (props.disabled) return
  const newValue = checked.value ? props.inactiveValue : props.activeValue
  innerValue.value = newValue
  emits('update:modelValue', newValue)
  emits('change', newValue)
}

watch(checked, (val) => {
  inputRef.value!.checked = val
})
watch(
  () => props.modelValue,
  (newValue) => {
    innerValue.value = newValue
  }
)

onMounted(() => {
  inputRef.value!.checked = checked.value
})

defineOptions({
  name: 'VSwitch',
  inheritAttrs: false,
})
</script>
<style scoped></style>
